package com.neusoft.yiyang.auth.controller;

import com.neusoft.yiyang.auth.service.CaptchaService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.Base64;

// 类级别注解：描述控制器功能
@Tag(name = "验证码接口", description = "生成和验证图形验证码")
@RestController
@RequestMapping("/captcha")
public class CaptchaController {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private CaptchaService captchaService;
    private static final long CAPTCHA_EXPIRE_SECONDS = 300;

    /**
     * 获取图形验证码
     */
    @Operation(summary = "获取图形验证码", description = "生成图形验证码，返回Base64图片和验证码唯一标识（captchaKey）")
    @GetMapping("/image")
    public Map<String, String> getCaptcha() throws IOException {
        String captchaText = captchaService.generateCaptchaText();
        String captchaKey = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(
                "captcha:" + captchaKey,
                captchaText,
                CAPTCHA_EXPIRE_SECONDS,
                TimeUnit.SECONDS
        );

        BufferedImage image = captchaService.generateCaptchaImage(captchaText);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "PNG", outputStream);
        String imageBase64 = Base64.getEncoder().encodeToString(outputStream.toByteArray());

        Map<String, String> result = new HashMap<>();
        result.put("captchaKey", captchaKey);
        result.put("imageBase64", "data:image/png;base64," + imageBase64);
        return result;
    }
}